package com.ruoyi.dr.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dr.domain.DrSellDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.dr.mapper.DrOwnerUnionMapper;
import com.ruoyi.dr.domain.DrOwnerUnion;
import com.ruoyi.dr.service.IDrOwnerUnionService;

/**
 * 归属信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-14
 */
@Service
public class DrOwnerUnionServiceImpl implements IDrOwnerUnionService {

    private static final Logger log = LoggerFactory.getLogger(DrSellDetailsServiceImpl.class);

    @Autowired
    private DrOwnerUnionMapper drOwnerUnionMapper;

    /**
     * 查询归属信息
     * 
     * @param id 归属信息主键
     * @return 归属信息
     */
    @Override
    public DrOwnerUnion selectDrOwnerUnionById(Long id)
    {
        return drOwnerUnionMapper.selectDrOwnerUnionById(id);
    }

    /**
     * 查询归属信息列表
     * 
     * @param drOwnerUnion 归属信息
     * @return 归属信息
     */
    @Override
    public List<DrOwnerUnion> selectDrOwnerUnionList(DrOwnerUnion drOwnerUnion)
    {
        return drOwnerUnionMapper.selectDrOwnerUnionList(drOwnerUnion);
    }

    /**
     * 新增归属信息
     * 
     * @param drOwnerUnion 归属信息
     * @return 结果
     */
    @Override
    public int insertDrOwnerUnion(DrOwnerUnion drOwnerUnion)
    {
        return drOwnerUnionMapper.insertDrOwnerUnion(drOwnerUnion);
    }

    /**
     * 修改归属信息
     * 
     * @param drOwnerUnion 归属信息
     * @return 结果
     */
    @Override
    public int updateDrOwnerUnion(DrOwnerUnion drOwnerUnion)
    {
        return drOwnerUnionMapper.updateDrOwnerUnion(drOwnerUnion);
    }

    /**
     * 批量删除归属信息
     * 
     * @param ids 需要删除的归属信息主键
     * @return 结果
     */
    @Override
    public int deleteDrOwnerUnionByIds(Long[] ids)
    {
        return drOwnerUnionMapper.deleteDrOwnerUnionByIds(ids);
    }

    /**
     * 删除归属信息信息
     * 
     * @param id 归属信息主键
     * @return 结果
     */
    @Override
    public int deleteDrOwnerUnionById(Long id)
    {
        return drOwnerUnionMapper.deleteDrOwnerUnionById(id);
    }


    @Override
    public String importOwnerUnion(List<DrOwnerUnion> ownerUnions, String operName){
        if (StringUtils.isNull(ownerUnions) || ownerUnions.size() == 0)
        {
            throw new ServiceException("导入归属表数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (DrOwnerUnion ownerUnion : ownerUnions) {
            try
            {
                // 验证是否存在这个用户
                DrOwnerUnion o = drOwnerUnionMapper.selectByAwemeId(ownerUnion);
                if (StringUtils.isNull(o)) {
                    if (StringUtils.isNull(ownerUnion.getTzOwner())) {
                        ownerUnion.setTzOwner("巨狮星选");
                    }
                    drOwnerUnionMapper.insertDrOwnerUnion(ownerUnion);
//                    userMapper.insertUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + " 条数据 导入成功");
                }
                // 如果有这个用户，归属人一样则不更新，需要手动更新
                else if (!StringUtils.equals(o.getOwner(), ownerUnion.getOwner())) {
//                    BeanValidators.validateWithException(validator, user);
//                    checkUserAllowed(u);
//                    checkUserDataScope(u.getUserId());
//                    deptService.checkDeptDataScope(user.getDeptId());
//                    user.setUserId(u.getUserId());
//                    user.setUpdateBy(operName);
//                    userMapper.updateUser(user);
//                    drOwnerUnionMapper.updateDrOwnerUnion(ownerUnion);
                    successNum++;
                    successMsg.append("<br/>" + ownerUnion.getAwemeId() + " 已有归属,更新不成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "条数据： " + ownerUnion.getAwemeId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }


    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<DrOwnerUnion> buildOwnerUnionTree(List<DrOwnerUnion> ownerUnions)
    {
        List<DrOwnerUnion> returnList = new ArrayList<>();
        List<Long> tempList = ownerUnions.stream().map(DrOwnerUnion::getId).collect(Collectors.toList());
        for (Iterator<DrOwnerUnion> iterator = ownerUnions.iterator(); iterator.hasNext();)
        {
            DrOwnerUnion ownerUnion = (DrOwnerUnion) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(ownerUnion.getParentId()))
            {
                recursionFn(ownerUnions, ownerUnion);
                returnList.add(ownerUnion);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = ownerUnions;
        }
        return returnList;
    }



    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<DrOwnerUnion> list, DrOwnerUnion t)
    {
        // 得到子节点列表
        List<DrOwnerUnion> childList = getChildList(list, t);
        t.setChildren(childList);
        for (DrOwnerUnion tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<DrOwnerUnion> list, DrOwnerUnion t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 得到子节点列表
     */
    private List<DrOwnerUnion> getChildList(List<DrOwnerUnion> list, DrOwnerUnion t)
    {
        List<DrOwnerUnion> tlist = new ArrayList<>();
        Iterator<DrOwnerUnion> it = list.iterator();
        while (it.hasNext())
        {
            DrOwnerUnion n = (DrOwnerUnion) it.next();
            if (n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
}
